﻿/*******************************************************************************
 * Copyright © 2016 DJY 版权所有
 * Author: DJY
 * Description: 后台管理系统
 * Website：http://www.djyweb.cn
*********************************************************************************/
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;

namespace DJY.Data
{
    public class DemoContext : DbContext
    {
        const string DefaultDbContextName = "DemoContext";

        const string DefaultMapperAssemblyName = "DJY.Mapping";

        static readonly Type EntityConfigType = typeof(EntityTypeConfiguration<>);

        public string DbContextName {
            get;
        }

        public string MapperAssemblyName
        {
            get;
        }

        static DemoContext()
        {
            Database.SetInitializer<DemoContext>(null);
        }

        public DemoContext():this(DefaultDbContextName)
        {
        }

        public DemoContext(string nameOfConnectionString)
            : base(nameOfConnectionString)
        {
            this.Configuration.AutoDetectChangesEnabled = false;
            this.Configuration.ValidateOnSaveEnabled = false;
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;

            DbContextName = nameOfConnectionString;
            MapperAssemblyName = DefaultMapperAssemblyName;

            int idx = DbContextName.IndexOf(".");
            if (idx > -1)
            {
                idx = DbContextName.LastIndexOf(".");
                MapperAssemblyName = $"DJY.{DbContextName.Substring(idx + 1)}.Mapping";
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Assembly asm = Assembly.Load(MapperAssemblyName);
            var mapTypes = asm.GetTypes()
            .Where(type => type.BaseType != null 
            && type.BaseType.IsGenericType 
            && type.BaseType.GetGenericTypeDefinition() == EntityConfigType);
            foreach (var type in mapTypes)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
            base.OnModelCreating(modelBuilder);
        }
    }
}
